package com.lixy.convert;


import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.slides.SaveFormat;
import com.aspose.words.Document;

import java.io.*;

/**
 * @author lishuai
 * @date 2021/09/27 09:31
 * @version: 1.0
 */
public class Office2Pdf {

    /**
     * 获取license 去除水印
     * @return
     */
    public static boolean getExcelLicense() {
        boolean result = false;
        try {
            InputStream is = Office2Pdf.class.getClassLoader().getResourceAsStream("\\license.xml");
            com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    private static boolean getWordLicense() {
        boolean result = false;
        try {
            InputStream is = Office2Pdf.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
            com.aspose.words.License aposeLic = new com.aspose.words.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取license 去除水印
     * @return
     */
    public static boolean getPPtLicense() {
        boolean result = false;
        try {
            InputStream is = Office2Pdf.class.getClassLoader().getResourceAsStream("\\license.xml");
            com.aspose.slides.License aposeLic = new com.aspose.slides.License();
            aposeLic.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * ppt 转为pdf 输出。
     *
     * @param sourceFilePath  excel文件
     * @param desFilePathd  pad 输出文件目录
     */
    public static void ppt2pdf(String sourceFilePath, String desFilePathd ){
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getPPtLicense()) {
            return;
        }
        try {
            FileInputStream fileInput = new FileInputStream(sourceFilePath);
            Presentation pres = new Presentation(fileInput);
            FileOutputStream out = new FileOutputStream(desFilePathd);
            pres.save(out, SaveFormat.Pdf);
            out.close();
            System.out.println("success");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static InputStream ppt2pdf(InputStream in) {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getPPtLicense()) {
            throw new RuntimeException("license不正确");
        }
        try {
            Presentation pres = new Presentation(in);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            pres.save(out, SaveFormat.Pdf);
            out.close();
            System.out.println("success");
            return new ByteArrayInputStream(out.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param wordPath 需要被转换的word全路径带文件名
     * @param pdfPath 转换之后pdf的全路径带文件名
     */
    public static void doc2pdf(String wordPath, String pdfPath) {
        if (!getWordLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
            return;
        }
        try {
            long old = System.currentTimeMillis();
            File file = new File(pdfPath); //新建一个pdf文档
            FileOutputStream os = new FileOutputStream(file);
            Document doc = new Document(wordPath); //Address是将要被转化的word文档
            doc.save(os, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            os.close();
            System.out.println("success"); //转化用时
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



    public static InputStream doc2pdf(InputStream in) {
        if (!getWordLicense()) {
            throw new RuntimeException("license不正确");
        }
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            Document doc = new Document(in); //Address是将要被转化的word文档
            doc.save(os, com.aspose.words.SaveFormat.PDF);//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
            os.close();
            System.out.println("success"); //转化用时
            return new ByteArrayInputStream(os.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * excel 转为pdf 输出。
     *
     * @param sourceFilePath  excel文件
     * @param desFilePathd  pad 输出文件目录
     */
    public static void excel2pdf(String sourceFilePath, String desFilePathd ){
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getExcelLicense()) {
            return;
        }
        try {
            Workbook wb = new Workbook(sourceFilePath);// 原始excel路径

            FileOutputStream fileOS = new FileOutputStream(desFilePathd);
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);


            int[] autoDrawSheets={3};
            //当excel中对应的sheet页宽度太大时，在PDF中会拆断并分页。此处等比缩放。
//            autoDraw(wb,autoDrawSheets);

            int[] showSheets={0};
            //隐藏workbook中不需要的sheet页。
            printSheetPage(wb,showSheets);
            wb.save(fileOS, pdfSaveOptions);
            fileOS.flush();
            fileOS.close();
            System.out.println("success");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static InputStream excel2pdf(InputStream in) {
        // 验证License 若不验证则转化出的pdf文档会有水印产生
        if (!getExcelLicense()) {
            throw new RuntimeException("license不正确");
        }
        try {
            Workbook wb = new Workbook(in);// 原始excel路径

            ByteArrayOutputStream fileOS = new ByteArrayOutputStream();
            PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
            pdfSaveOptions.setOnePagePerSheet(true);


            int[] autoDrawSheets={3};
            //当excel中对应的sheet页宽度太大时，在PDF中会拆断并分页。此处等比缩放。
//            autoDraw(wb,autoDrawSheets);

            int[] showSheets={0};
            //隐藏workbook中不需要的sheet页。
            printSheetPage(wb,showSheets);
            wb.save(fileOS, pdfSaveOptions);
            fileOS.flush();
            fileOS.close();
            System.out.println("success");
            return new ByteArrayInputStream(fileOS.toByteArray());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 设置打印的sheet 自动拉伸比例
     * @param wb
     * @param page 自动拉伸的页的sheet数组
     */
    public static void autoDraw(Workbook wb,int[] page){
        if(null!=page&&page.length>0){
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
                wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
            }
        }
    }


    /**
     * 隐藏workbook中不需要的sheet页。
     * @param wb
     * @param page 显示页的sheet数组
     */
    public static void printSheetPage(Workbook wb,int[] page){
        for (int i= 1; i < wb.getWorksheets().getCount(); i++)  {
            wb.getWorksheets().get(i).setVisible(false);
        }
        if(null==page||page.length==0){
            wb.getWorksheets().get(0).setVisible(true);
        }else{
            for (int i = 0; i < page.length; i++) {
                wb.getWorksheets().get(i).setVisible(true);
            }
        }
    }

    public static void main(String[] args) {
        /**
         * 36605 ms
         */
        long begin = System.currentTimeMillis();
        excel2pdf("E:\\img\\功能需求列表.xlsx","D:\\out\\功能需求列表.pdf");
        ppt2pdf("E:\\img\\开发分享.pptx","D:\\out\\开发分享.pdf");
        doc2pdf("E:\\img\\音频处理器中控命令v17.doc","D:\\out\\音频处理器中控命令v17.pdf");
        doc2pdf("E:\\img\\权限管理模块设计.docx","D:\\out\\权限管理模块设计.pdf");
        System.out.println(System.currentTimeMillis() - begin);
    }

}
